package www.reagnetbox.com.util;

public class AsciiUtils {

    // 字符串转换为Ascii
    public static String stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            sbu.append(Integer.toHexString((int) chars[i]));
        }
        return sbu.toString();
    }


    // 字符串转换为Ascii含有逗号
    public static String stringToAsciiWithAppendComma(String value) {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return sbu.toString();
    }

    // Ascii转换为字符串
    public static String asciiToString(String value) {
        StringBuffer sb = new StringBuffer();
        value = value.trim();
        if (value.length() % 2 > 0) {
            return null;
        }

        int index = 0;
        while (index < value.length()) {
            sb.append((char) Integer.parseInt(value.substring(index, index + 2), 16));
            index = index + 2;
        }

        return sb.toString();
    }
}
